<?php

namespace App\Http\Controllers;

use App\Models\ClaimProject;
use App\Models\UserClaimProject;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class ClaimProjectApplyController extends Controller
{
    public function index(Request $request, $project_id) {
        ClaimProject::findOrFail($project_id);

        $perPage = $request->get('perPage', 10);
        $query = UserClaimProject::with('project')->where('project_id', '=', $project_id);
        $query->orderBy('created_at', 'desc');
        $asExcel = $request->get("asExcel", false);
        $info = null;
        if($asExcel){
            // 保持和分页的结构一致，设置data=>{}
            $tmp = $query->get()->toArray();
            $info = array(
                'data' => $tmp
            );
        }else {
            $info = $query->paginate($perPage)->toArray();
        }

        if ($asExcel){
            return Excel::create(time(),function($excel) use ($info){

                $excel->sheet('认领人员信息', function($sheet) use ($info){

                    $sheet->appendRow(1, array(
                        '团队', '联系人', '联系电话', '邮箱	', '报名时间'
                    ));

                    for ($i = 0;$i<count($info['data']);$i++){
                        $item = $info['data'][$i];
                        $sheet->appendRow($i+2,array(
                            $item['team_name'],
                            $item['contact_name'],
                            $item['contact_phone'],
                            $item['contact_email'],
                            $item['created_at']
                        ));
                    }
                });
            })->export('xls');
        }


        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }


    public function destroy(Request $request, $project_id, $id)
    {
        ClaimProject::findOrFail($project_id);

        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        if (UserClaimProject::whereRaw('id IN (?)', [$ids])->delete()) {
            return $this->returnJSON($ids, 0, '删除成功');
        } else {
            return $this->returnJSON(null, 1, "删除失败");
        }
    }

}
